<template>
  <!-- MemberCoupon 优惠券 -->
  <PageContainer>
    <view class="container">
      <Tabs v-model="currentTab">
        <Header title="福利券" :default-slot-content-height="78" :is-box-shadow="false">
          <TabNav tabBarColor="#D7B87C" />
        </Header>
        <TabsItem name="我领取的" :value="0">
          <Paglist
            v-model="dataList_1"
            :is-init-api="false"
            :parame="{}"
            @register="register_1"
            :scroll-top-bottom="260"
            :is-show-loadmore="dataList_1.length > 1"
          >
            <template v-for="v in dataList_1" :key="v.id">
              <CouponItem
                :img="v.couponCover"
                :title="v.couponName"
                :times="[
                  {
                    label: '领取时间',
                    value: v.createTime,
                  },
                  {
                    label: '有效时间',
                    value: `${v.validityStartTime} - ${v.validityEndTime}`,
                  },
                ]"
                :show-item-bottom="true"
                @click="toDetails(v.couponId)"
              >
                <template #itemBottom>
                  <view class="coupon-status">
                    <template v-for="(item, i) in couponStatusText(v.status)" :key="i">
                      <text :style="{ color: item.color }">{{ item.text }}</text>
                    </template>
                  </view>
                </template>
              </CouponItem>
            </template>
          </Paglist>
        </TabsItem>
        <TabsItem name="我发布的" :value="1">
          <Paglist
            v-model="dataList_2"
            :is-init-api="false"
            :parame="{}"
            @register="register_2"
            :scroll-top-bottom="260"
            :is-show-loadmore="dataList_2.length > 1"
          >
            <template v-for="v in dataList_2" :key="v.id">
              <CouponItem
                :img="v.couponCover"
                :title="v.name"
                :times="[
                  {
                    label: '发布时间',
                    value: v.createTime,
                  },
                  {
                    label: '有效时间',
                    value: `${v.validityStartTime} - ${v.validityEndTime}`,
                  },
                ]"
                :show-item-bottom="true"
                @click="toEdit(v.id)"
              >
                <template #midText>
                  <text class="item-text_mid">
                    发放数量: {{ v.couponNumber }}(已领{{ v.assignNumber }}，已使用{{
                      v.usedNumber
                    }}）
                  </text>
                </template>
                <template #itemBottom>
                  <view class="btn-group">
                    <template>
                      <button class="btn" type="none" @click.stop="handleDisplay(v)">
                        {{ v.display === 1 ? '上架' : '下架' }}
                      </button>
                    </template>
                    <button
                      v-if="v.couponRole === MemberCouponPermissionsEnum.PRIVACY"
                      class="btn"
                      @click.stop="setShareInfo(v)"
                      open-type="share"
                      type="none"
                    >
                      分享
                    </button>
                    <button class="btn" type="none" @click.stop="toRecord(v.id)">领券记录</button>
                  </view>
                </template>
              </CouponItem>
            </template>
          </Paglist>

          <template v-if="cocInfo">
            <image
              class="float-btn"
              src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/floatIcon/create-icon.png"
              @click="createMemberCoupon"
            />
            <TButtonGroup>
              <TButton
                class="gutter-btn"
                text="立即核销"
                custom-class="cardBtn"
                @click="onSubmit"
              />
            </TButtonGroup>
          </template>
        </TabsItem>
      </Tabs>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  MemberCoupon  福利券 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import Paglist from '@/components/Paglist/index.vue';
  import Header from '@/components/Header/index.vue';
  import dictionary from '@/utils/dictionary';
  import CouponItem from './components/CouponItem.vue';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { useConList } from '@/components/Paglist/useConList';
  import { UniEmitNameEnum } from '@/enums/uniEmitEnum';
  import { provide, ref, watch } from 'vue';
  import { PotentialClientsTypeEnum } from '@/enums/commercializeEnum';
  import { onPageScroll, onShareAppMessage, onUnload } from '@dcloudio/uni-app';
  import { navigateTo, onLoad } from '@/router';
  import { type MemberCouponListResult, type ReceivedCouponResult } from '@/api/memberCoupon/types';
  import { memberCouponDisplay, memberCouponList, receivedCoupon } from '@/api/memberCoupon';
  import { addProspectiveMembers, Toast } from '@/utils';
  import {
    MemberCouponPermissionsEnum,
    MemberCouponIsDisplayEnum,
    CouponOrderStatusEnum,
  } from '@/enums/memberCouponEnum';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { useAppShare } from '@/hooks/core/useAppShare';

  const currentTab = ref(0);
  const { setWxSharePath } = useAppShare();
  const dataList_1 = ref<ReceivedCouponResult[]>([]);
  const [register_1, { refresh: refresh_1 }] = useConList({
    api: receivedCoupon,
  });

  const dataList_2 = ref<MemberCouponListResult[]>([]);
  const [register_2, { refresh: refresh_2 }] = useConList({
    api: memberCouponList,
  });

  watch(currentTab, tabChange);

  const { cocInfo } = useUserStoreWithOut();

  function tabChange(index: number) {
    switch (index) {
      case 0:
        !dataList_1.value.length && refresh_1();
        break;
      case 1:
        !dataList_2.value.length && refresh_2();
        if (!cocInfo)
          addProspectiveMembers({
            type: PotentialClientsTypeEnum.COUPON,
          });
        break;
    }
  }

  const couponStatusText = (status: CouponOrderStatusEnum) => {
    const dicts = dictionary.getLocal('couponReceivedStatus');
    const item = dicts.find((v) => v.dictValue == status);
    return [
      {
        color: item?.statusColor,
        text: item?.dictLabel,
      },
    ];
  };

  const createMemberCoupon = () => {
    const list = ['创建'];
    if (dataList_2.value.length) {
      list.push('选择历史素材');
    }
    uni.showActionSheet({
      itemList: list,
      success: ({ tapIndex }) => {
        if (tapIndex === 0) {
          navigateTo({
            name: 'createMemberCoupon',
            options: {
              success: refresh_2,
            },
          });
        } else {
          navigateTo({ name: 'couponChooseHistory' });
        }
      },
    });
  };

  /** 上架 / 下架 */
  function handleDisplay(item: MemberCouponListResult) {
    uni.showModal({
      title: '提示',
      content: `是否立即${item.display === MemberCouponIsDisplayEnum.NO ? '上架' : '下架'}?`,
      success: ({ confirm }) => {
        if (confirm) {
          const display = Number(!item.display);
          memberCouponDisplay({
            id: item.id,
            display,
          }).then(() => {
            item.display = display;
            Toast('操作成功', 'success', 1500, false);
          });
        }
      },
    });
  }

  function toDetails(id: number) {
    navigateTo({
      name: 'memberCouponDetails',
      options: {
        id,
      },
    });
  }

  function toEdit(id: number) {
    navigateTo({
      name: 'createMemberCoupon',
      options: {
        id,
        isEdit: true,
      },
    });
  }

  function toRecord(id: number) {
    navigateTo({
      name: 'recordCouponCollection',
      options: {
        couponId: id,
      },
    });
  }

  function onSubmit() {
    navigateTo({ name: 'cancelAfterVerification' });
  }

  wx.hideShareMenu({
    menus: ['shareAppMessage', 'shareTimeline'],
  });

  const shareInfo = ref<MemberCouponListResult>();

  function setShareInfo(item: MemberCouponListResult) {
    shareInfo.value = item;
  }

  onShareAppMessage(() => {
    const promise = new Promise((resolve) => {
      const timer = setInterval(() => {
        console.log(shareInfo.value);
        if (shareInfo.value) {
          const { id, name, couponCover } = shareInfo.value;
          resolve({
            title: name,
            path: setWxSharePath({
              name: 'memberCouponDetails',
              options: {
                id,
                isShare: true,
              },
            }),
            imageUrl: couponCover,
          });
          clearInterval(timer);
        }
      }, 10);
    });
    return {
      promise,
    } as any;
  });

  onLoad(() => {
    tabChange(currentTab.value);
    uni.$on(UniEmitNameEnum.REFRESHPREVIOUSPAGE, () => {
      refresh_2();
    });
  });
  onUnload(() => {
    uni.$off(UniEmitNameEnum.REFRESHPREVIOUSPAGE);
  });
  onPageScroll(() => {});
  provide('api', null);
</script>

<style lang="scss" scoped>
  .item-text_mid {
    color: #2878ff;
    font-size: 24rpx;
  }

  .coupon-status {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 24rpx;
  }

  .btn-group {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .btn {
      width: 142rpx;
      height: 42rpx;
      background: #e9e3b5;
      border-radius: 10rpx;
      line-height: 42rpx;
      text-align: center;
      color: #333333;
      font-size: 24rpx;
      margin-left: 20rpx;
    }
  }

  .float-btn {
    width: 108rpx;
    height: 108rpx;
    position: fixed;
    right: 30rpx;
    bottom: calc(env(safe-area-inset-bottom) + 360rpx);
  }
</style>
